package com.pride1952.myoptimusx3;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.text.InputFilter;
import android.text.InputType;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;


public class ScanNewDevicesActivity extends Activity {

    private static final int REQUEST_ENABLE_BT = 1;
    // Stops scanning after 10 seconds.
    private static final long SCAN_PERIOD = 10000;
    private boolean mScanning;
    private Handler mHandler=new Handler();

    private TitleFragment mTitle;
    private PopupWindow mPopWaiting;

    private BluetoothAdapter mBluetoothAdapter;
    private ListView mListView;
    private LeDeviceListAdapter mLeDeviceListAdapter;

    private SetDeviceCallback setDeviceCallback = new SetDeviceCallback();
    private String devicePassword;

    private IntentFilter intentFilter(){
        IntentFilter intentFilter=new IntentFilter();
        intentFilter.addAction(BluetoothLeService.mACTION_PASSWORD_CORRECT);
        intentFilter.addAction(BluetoothLeService.mACTION_PASSWORD_WRONG);
        return intentFilter;
    }
    private BroadcastReceiver bcReceiver=new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action)
            {
                case BluetoothLeService.mACTION_PASSWORD_CORRECT:
                    Toast.makeText(ScanNewDevicesActivity.this, "密码正确", Toast.LENGTH_SHORT).show();
                    mPopWaiting.dismiss();
                    setDeviceCallback.setPref();
                    finish();
                    break;

                case BluetoothLeService.mACTION_PASSWORD_WRONG:
                    Toast.makeText(ScanNewDevicesActivity.this, "密码错误", Toast.LENGTH_SHORT).show();
                    mPopWaiting.dismiss();
                    break;

                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan_new_devices);

        initBlueTooth();
        initTitle();

        initWidgets();
    }

    private void initBlueTooth(){
        // Initializes a Bluetooth adapter.  For API level 18 and above, get a reference to
        // BluetoothAdapter through BluetoothManager.
        final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();

        // Checks if Bluetooth is supported on the device.
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
    }

    private void initWidgets(){
        mListView=(ListView)findViewById(R.id.listView_scan_new);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                final BluetoothDevice device = mLeDeviceListAdapter.getDevice(position);
                if (device == null) return;

                final String deviceAddress = device.getAddress();

                //弹出填写密码的dialog
                final EditText mEditPassword=new EditText(ScanNewDevicesActivity.this);
                mEditPassword.setInputType(InputType.TYPE_CLASS_NUMBER);
                mEditPassword.setFilters(new InputFilter[]{new InputFilter.LengthFilter(4)});
                new AlertDialog.Builder(ScanNewDevicesActivity.this)
                        .setTitle("请输入四位数密码")
                        .setIcon(android.R.drawable.ic_dialog_info)
                        .setView(mEditPassword)
                        .setPositiveButton("确定",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        //点击确定按钮之后
                                        devicePassword =mEditPassword.getText().toString();

                                        if(devicePassword.length() == 4){

                                            Intent btServiceIntent = new Intent(ScanNewDevicesActivity.this, BluetoothLeService.class);
                                            btServiceIntent.setAction("CHECK_PASSWORD");
                                            btServiceIntent.putExtra("DEVICE_ADDRESS", deviceAddress);
                                            btServiceIntent.putExtra("DEVICE_PASSWORD", devicePassword);
                                            startService(btServiceIntent);

                                            setDeviceCallback.setDevice(deviceAddress, devicePassword);

                                            View view2 = getLayoutInflater().inflate(R.layout.popupwindow_waiting, null);
                                            TextView txtWaiting=(TextView)view2.findViewById(R.id.waiting_txt_waiting);
                                            txtWaiting.setText("正在验证密码");
                                            mPopWaiting = new PopupWindow(view2, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                                            mPopWaiting.showAtLocation(findViewById(R.id.activity_scan_new_devices), Gravity.CENTER,0,0);
                                            //todo 如果用户选择的设备不是我们的手环，则这里会进入死胡同
                                        } else Toast.makeText(ScanNewDevicesActivity.this, "请输入四位数密码", Toast.LENGTH_LONG).show();
                                    }
                                })
                        .setNegativeButton("取消",null)
                        .show();
                //TODO 是否还有后续工作？有的话请完成……

            }
        });
    }

    private void initTitle(){
        FragmentManager fm=getFragmentManager();
        FragmentTransaction transaction=fm.beginTransaction();
        Bundle bundle=new Bundle();
        bundle.putString("Title","添加新设备");
        bundle.putBoolean("IsBack",true);
        mTitle=new TitleFragment();
        mTitle.setArguments(bundle);
        transaction.replace(R.id.title_scan_new, mTitle);
        transaction.commit();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_scan_new_devices, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(bcReceiver, intentFilter());

        // Ensures Bluetooth is enabled on the device.  If Bluetooth is not currently enabled,
        // fire an intent to display a dialog asking the user to grant permission to enable it.
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }

        // Initializes list view adapter.
        mLeDeviceListAdapter = new LeDeviceListAdapter();
        mListView.setAdapter(mLeDeviceListAdapter);
        scanLeDevice(true);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // User chose not to enable Bluetooth.
        if (requestCode == REQUEST_ENABLE_BT && resultCode == Activity.RESULT_CANCELED) {
            finish();
            return;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(bcReceiver);
        scanLeDevice(false);
        mLeDeviceListAdapter.clear();
    }

    private void scanLeDevice(final boolean enable) {
        if (enable) {
            // Stops scanning after a pre-defined scan period.
//            mHandler.postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    mScanning = false;
//                    mBluetoothAdapter.stopLeScan(mLeScanCallback);
//                    invalidateOptionsMenu();
//                }
//            }, SCAN_PERIOD);

            mScanning = true;
            mBluetoothAdapter.startLeScan(mLeScanCallback);
        } else {
            mScanning = false;
            mBluetoothAdapter.stopLeScan(mLeScanCallback);
        }
        invalidateOptionsMenu();
    }

    // Adapter for holding devices found through scanning.
    private class LeDeviceListAdapter extends BaseAdapter {
        private ArrayList<BluetoothDevice> mLeDevices;
        private LayoutInflater mInflator;

        public LeDeviceListAdapter() {
            super();
            mLeDevices = new ArrayList<BluetoothDevice>();
            mInflator = ScanNewDevicesActivity.this.getLayoutInflater();
        }

        public void addDevice(BluetoothDevice device) {
            if(!mLeDevices.contains(device)) {
                mLeDevices.add(device);
            }
        }

        public BluetoothDevice getDevice(int position) {
            return mLeDevices.get(position);
        }

        public void clear() {
            mLeDevices.clear();
        }

        @Override
        public int getCount() {
            return mLeDevices.size();
        }

        @Override
        public Object getItem(int i) {
            return mLeDevices.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            ViewHolder viewHolder;
            // General ListView optimization code.
            if (view == null) {
                view = mInflator.inflate(R.layout.listitem_device, null);
                viewHolder = new ViewHolder();
                viewHolder.deviceAddress = (TextView) view.findViewById(R.id.device_address);
                viewHolder.deviceName = (TextView) view.findViewById(R.id.device_name);
                view.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) view.getTag();
            }

            BluetoothDevice device = mLeDevices.get(i);
            final String deviceName = device.getName();
            if (deviceName != null && deviceName.length() > 0)
                viewHolder.deviceName.setText(deviceName);
            else
                viewHolder.deviceName.setText(R.string.unknown_device);
            viewHolder.deviceAddress.setText(device.getAddress());

            return view;
        }
    }

    // Device scan callback.
    private BluetoothAdapter.LeScanCallback mLeScanCallback =
            new BluetoothAdapter.LeScanCallback() {

                @Override
                public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mLeDeviceListAdapter.addDevice(device);
                            mLeDeviceListAdapter.notifyDataSetChanged();
                        }
                    });
                }
            };

    static class ViewHolder {
        TextView deviceName;
        TextView deviceAddress;
    }

    private class SetDeviceCallback{
        String deviceAddress = null;
        String devicePassword = null;

        void setDevice(String deviceAddress, String devicePassword){
            this.deviceAddress = deviceAddress;
            this.devicePassword = devicePassword;
        }

        void setPref(){
            SharedPreferences mPreferences=getSharedPreferences("Devices", MODE_PRIVATE);
            SharedPreferences.Editor mEditor=mPreferences.edit();
            mEditor.putString("address", deviceAddress);
            mEditor.putString("password", devicePassword);
            mEditor.apply();
        }
    }
}